/**
 * Created by li hong 2017/10/10 0025.
 */

$(function () {
    var table = new tableFactory();
    addListeners(table);
});

function tableFactory() {
    var me = this;
    me.data = null;
    var init = function () {
        $("#fanCapacity").bootstrapTable({
            method: 'get',					  //请求方式（*）
            striped: true,					  //是否显示行间隔色
            cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,				   //是否显示分页（*）
            sortable: true,					 //是否启用排序
            sortOrder: "asc",				   //排序方式
            sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,					   //初始化加载第一页，默认第一页
            search: true,					   //是否显示表格搜索，只能进行客户端搜索
            strictSearch: false,                //true为全匹配，false为模糊查询
            showColumns: false,				  //是否显示筛选列按钮
           // showFooter:true,
            showRefresh: false,				  //是否显示刷新按钮
            clickToSelect: true,				//是否启用点击选中行
            showToggle: false,					//是否显示详细视图和列表视图的切换按钮
            cardView: false,					//是否显示详细视图
            detailView: false,				   //是否显示父子表
            singleSelect: true,
            height: 'auto',
            pageSize: 10,
            pageList: [5,10,20],
            columns: [{
                title: '装机容量(MW)', field: 'capacity', align: 'center', valign: 'middle', sortable: true,
                formatter:function (value, row, index) {
                    return value/1000;
                }
            },{
                title: '风机型号', field: 'fanmodel', align: 'center'
            }, {
                title: '风机台数', field: 'fannum', align: 'center'
            }]
        });
        me.loadData();
    }
    init();
}

tableFactory.prototype = {
    loadData: function () {
        var farmid = $('#selectFarm', window.parent.document).val();//获取父页面的元素
        var p = {
            "farmid":farmid
        };
        var me = this;
        $.getJSON('../fanCapacityManage/getInfo', p, function (_data) {
            me.data = _data;
            $("#fanCapacity").bootstrapTable("load", _data.list);
            $("#WfFanInfo").text("总容量："+_data.map.capacity/1000+",风机总台数："+_data.map.fannum);
        })
    },
    save: function () {
        var me = this;
        var html = [];
        html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
        html.push('<tr><td>部门名称：</td><td><input type="text" class="form-control" id="new-deptname" /></td></tr>');
        html.push('<tr><td>部门描述：</td><td><input type="text" class="form-control" id="new-deptdesc" /></td></tr>');
        html.push('<tr><td>部门地址：</td><td><input type="text" class="form-control" id="new-deptaddress" /></td></tr>');
        html.push('<tr><td>上级部门：</td><td><select type="text" class="form-control" id="new-deptparentid">');
        html.push('<option value="">无</option>');
        $.each(me.data, function (index, item) {
            html.push('<option value="' + item.deptparentid + '">' + item.deptname + '</option>');
        });
        html.push('</select></td></tr>');
        html.push('</table></div>');

        layer.open({
            type: 1,
            area: '500px',
            title: '添加部门',
            btn: ['确定'],
            //shadeClose: true,//开启遮罩关闭
            content: html.join(''),
            yes: function (index) {
                var p = {
                    //departmentid: me.maxId + 1,
                    deptparentid: $("#new-deptparentid").val(),
                    deptname: $("#new-deptname").val(),
                    deptdesc: $("#new-deptdesc").val(),
                    address: $("#new-deptaddress").val(),
                    remarks:""
                };
                layer.close(index);
                $.ajax({
                    url : "../departmentManage/insert",
                    type : "post",
                    contentType : "application/json",
                    dataType : "json",
                    data : JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                    success : function(data) {
                        if (data === true) {
                            me.loadData();
                            layer.msg("添加成功！", {icon: 1});
                        } else {
                            layer.msg("添加失败！", {icon: 2});
                        }
                    },
                    error :function(){
                        alert("添加失败");
                    }
                });
                /*$.post("department/insert", p, function (data) {
                    if (data === true) {
                        me.loadData();
                        layer.msg("添加成功！", {icon: 1});
                    } else {
                        layer.msg("添加失败！", {icon: 2});
                    }
                })*/

            }
        });
    },
    delete: function () {
        var me = this;
        var selects = $('#department').bootstrapTable("getSelections");
        if (selects.length > 0) {
            layer.confirm('确定删除?', {icon: 3, title:'提示'}, function (index) {
                //do something
                var deletes = [];
                var id;
                $.each(selects, function (index, item) {
                    deletes.push({
                        departmentid: item.departmentid,
                        deptparentid: item.deptparentid,
                        deptname: item.deptname,
                        deptdesc: item.deptdesc,
                        address: item.address,
                        remarks: ""
                    });
                    id = item.departmentid;
                    //alert(item.departmentid+""+item.deptname+item.deptdesc+item.address+item.deptparentid);
                    // alert(id);
                });
                $.ajax({
                    url: '../departmentManage/deleteOne',
                    type: 'post',
                    contentType : 'application/json;charset=utf-8', //设置请求头信息
                    dataType: 'json',
                    data: /*{"id":id},*/JSON.stringify(deletes),
                    success: function (data) {
                        if (data === true) {
                            me.loadData();
                            layer.msg("删除成功！", {icon: 1});
                        }
                    }
                });
                layer.close(index);
            });
        } else {
            layer.msg("请选择要删除的部门！", {icon: 0});
        }
    },
    edit: function () {
        var me = this;
        var selects = $('#department').bootstrapTable("getSelections");
        var len = selects.length;
        if (len === 1) {
            var editItem = selects[0];
            var html = [];
            html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
            html.push('<tr><td>部门名称：</td><td><input type="text" class="form-control" id="edit-deptname" /></td></tr>');
            html.push('<tr><td>部门描述：</td><td><input type="text" class="form-control" id="edit-deptdesc" /></td></tr>');
            html.push('<tr><td>部门区域：</td><td><input type="text" class="form-control" id="edit-deptaddress" /></td></tr>');
            html.push('<tr><td>上级部门：</td><td><select type="text" class="form-control" id="edit-deptparentid">');
            html.push('<option value="">无</option>');
            $.each(me.data, function (index, item) {
                html.push('<option value="' + item.deptparentid + '">' + item.deptname + '</option>');
            });
            html.push('</select></td></tr>');
            html.push('</table></div>');

            layer.open({
                type: 1, area: '500px', title: '修改部门', btn: ['确定'],
                content: html.join(''),
                success: function () {
                    $('#edit-deptname').val(editItem.deptname);
                    $('#edit-deptdesc').val(editItem.deptdesc);
                    $('#edit-deptaddress').val(editItem.address);
                    $('#edit-deptparentid').val(editItem.deptparentid);
                },
                yes: function (index) {
                    var p = {
                        departmentid: editItem.departmentid,
                        deptname: $("#edit-deptname").val(),
                        deptdesc: $("#edit-deptdesc").val(),
                        address: $("#edit-deptaddress").val(),
                        REMARKS:"",
                        deptparentid: $("#edit-deptparentid").val()
                    };
                    layer.close(index);
                    $.ajax({
                        url : "../departmentManage/update",
                        type : "POST",
                        contentType : "application/json",
                        dataType : "json",
                        data : JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                        success : function(data) {
                            if (data === true) {
                                me.loadData();
                                layer.msg("修改成功！", {icon: 1});
                            } else {
                                layer.msg("修改失败！", {icon: 2});
                            }
                        },
                        error :function(){
                            alert("添加失败");
                        }
                    });
                }
            });
        } else if (len > 1){
            layer.msg("只能选择一个部门！", {icon: 0});
        } else if (len === 0) {
            layer.msg("请选择要修改的部门！", {icon: 0});
        }
    }
};

function addListeners (tableObj) {
    $('#btn-add').off('click');
    $('#btn-delete').off('click');
    $('#btn-edit').off('click');
    $('#btn-add').on('click', function () {
        tableObj.save();
    });
    $('#btn-delete').on('click', function () {
        tableObj.delete();
    });
    $('#btn-edit').on('click', function () {
        tableObj.edit();
    });
}
